package org.springblade.mach.utils;

import io.minio.MinioClient;
import io.minio.errors.*;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springblade.core.oss.props.OssProperties;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.mach.entity.ReadExcelEntity;
import org.springblade.mach.service.IDrawingUploadService;
import org.springblade.mach.service.impl.DrawingUploadServiceImpl;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.resource.entity.Oss;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author LY
 * @version 1.0
 * @date 2021/3/10 14:10
 */
@Component
@AllArgsConstructor
public class ExcelUtils {
	// 对象存储对象
	private OssBuilder ossBuilder;
	// 获取wb
	public static Workbook getWb(MultipartFile mf){
		String filepath = mf.getOriginalFilename();
		String ext = filepath.substring(filepath.lastIndexOf("."));
		Workbook wb = null;
		try {
			InputStream is = mf.getInputStream();
			if(StringUtil.endsWithIgnoreCase(ext, ".xls")){
				wb = new HSSFWorkbook(is);
			}else if(StringUtil.endsWithIgnoreCase(ext, ".xlsx")){
				wb = new XSSFWorkbook(is);
			}else{
				wb=null;
			}
		} catch (FileNotFoundException e) {

		} catch (IOException e) {

		}
		return wb;
	}

	// 获取服务器上文件的wb
	public static Workbook getServerWb(String fileName, InputStream is){
		String ext = fileName.substring(fileName.lastIndexOf("."));
		Workbook wb = null;
		try {
			if(StringUtil.endsWithIgnoreCase(ext, ".xls")){
				wb = new HSSFWorkbook(is);
			}else if(StringUtil.endsWithIgnoreCase(ext, ".xlsx")){
				wb = new XSSFWorkbook(is);
			}else{
				wb=null;
			}
		} catch (FileNotFoundException e) {

		} catch (IOException e) {

		}
		return wb;
	}

	//根据Cell类型设置数据
	public static Object getCellFormatValue(Cell cell) {
		Object cellvalue = "";
		if (cell != null) {
			switch (cell.getCellType()) {
				case Cell.CELL_TYPE_NUMERIC:
				case Cell.CELL_TYPE_FORMULA: {
					if (DateUtil.isCellDateFormatted(cell)) {
						Date date = cell.getDateCellValue();
						cellvalue = date;
					} else {
						cellvalue = (int)cell.getNumericCellValue();
					}
					break;
				}
				case Cell.CELL_TYPE_STRING:
					cellvalue = cell.getRichStringCellValue().getString();
					break;
				default:
					cellvalue = "";
			}
		} else {
			cellvalue = "";
		}
		return cellvalue;
	}

	// 转化excel中单元格中格式
	public static String getStringVal(Cell cell){
		switch (cell.getCellType()){
			case Cell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
			case Cell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
			case Cell.CELL_TYPE_NUMERIC:
				cell.setCellType(Cell.CELL_TYPE_STRING);
				return cell.getStringCellValue();
			case Cell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			default:
				return "";
		}
	}

	// 检查
	public int checkRowError(Cell cell){
		if (cell==null || cell.equals("") || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
			return -1;
		}
		return 1;
	}

	// 读取excel中每一行的数据
	public ReadExcelEntity readExcelRow(Row row){
		// 根节点bom信息
		ReadExcelEntity readExcelEntity = new ReadExcelEntity();
		if (checkRowError(row.getCell(1)) == 1) {
			String drawingNumber =  getStringVal(row.getCell(1));
			readExcelEntity.setDrawingNumber(drawingNumber);
		}
		if (checkRowError(row.getCell(2)) == 1) {
			String drawingName = getStringVal(row.getCell(2));
			readExcelEntity.setDrawingName(drawingName);
		}
		if (checkRowError(row.getCell(3)) == 1) {
			String num =  getStringVal(row.getCell(3));
			readExcelEntity.setBomNum(num);
		}
		if (checkRowError(row.getCell(4)) == 1) {
			String material = getStringVal(row.getCell(4));
			readExcelEntity.setMaterial(material);
		}
		if (checkRowError(row.getCell(5)) == 1) {
			String singleWeight =  getStringVal(row.getCell(5));
			readExcelEntity.setSingleWeight(singleWeight);
		}
		if (checkRowError(row.getCell(6)) == 1) {
			String sumWeight =  getStringVal(row.getCell(6));
		}
		if (checkRowError(row.getCell(7)) == 1) {
			String drawingProperty =  getStringVal(row.getCell(7));
			readExcelEntity.setDrawingProperty(drawingProperty);
		}
		if (checkRowError(row.getCell(8)) == 1) {
			String remark = getStringVal(row.getCell(8));
			readExcelEntity.setRemark(remark);
		}
		if (checkRowError(row.getCell(9)) == 1) {
			String characOne =  getStringVal(row.getCell(9));
			readExcelEntity.setCharacOne(characOne);
		}
		if (checkRowError(row.getCell(10)) == 1) {
			String characTwo =  getStringVal(row.getCell(10));
			readExcelEntity.setCharacTwo(characTwo);
		}
		if (checkRowError(row.getCell(11)) == 1) {
			String charaThree = getStringVal(row.getCell(11));
			readExcelEntity.setCharacThree(charaThree);
		}
		return readExcelEntity;
//			String fileName = bomExcelByUploadId.get(i).getName();
//			ObjectStat objectStat = minioClient.statObject(ossProperties.getBucketName(), fileName);
//			response.setContentType(objectStat.contentType());
//			response.setCharacterEncoding("UTF-8");
//			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//			InputStream is = minioClient.getObject(ossProperties.getBucketName(), fileName);
//			IOUtils.copy(is,response.getOutputStream());
	}

	// 读取excel中的内容 List<x>中
	public List<ReadExcelEntity> getExcelEntityList(String bucket, String fileNameServer) throws InvalidPortException, InvalidEndpointException, IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
		Oss oss = ossBuilder.getOss(AuthUtil.getTenantId(), StringPool.EMPTY);
		MinioClient minioClient = new MinioClient(oss.getEndpoint(),oss.getAccessKey(),oss.getSecretKey());
		InputStream is = minioClient.getObject(bucket, fileNameServer);
		Workbook wb = getServerWb(fileNameServer, is);
		Sheet sheetAt = wb.getSheetAt(0);
		List<ReadExcelEntity> readExcelEntityList = new ArrayList<>();
		// 读取内容
		for (int j = 1; j <= sheetAt.getPhysicalNumberOfRows() ; j++) {
			Row row = sheetAt.getRow(j);
			if(row == null){
				continue;
			}
			if (checkRowError(row.getCell(1)) != 1) {
				continue;
			}
			// 保存bom信息
			ReadExcelEntity readExcelEntity = this.readExcelRow(row);
			readExcelEntityList.add(readExcelEntity);
		}
		return readExcelEntityList;

	}





}
